const md5 = require('md5')
const jwt = require('jsonwebtoken')
const uuid = require('uuid')
const util = require('util')

module.exports = {


  friendlyName: 'Login',


  description: 'Login user.',


  inputs: {
    loginName: {
      description: '用户名',
      type: 'string',
      required: true
    },
    password: {
      description: '用户密码',
      type: 'string',
      required: true
    }
  },

  exits: {

  },


  fn: async function (inputs) {
    try{
      var loginName = inputs.loginName
      var password = md5(inputs.password)

      var loginInfo = await Login.findOne({loginName:loginName,password:password})

      if(!loginInfo){
        return 'error_user'
      }

      var userId = loginInfo.userId
      //var userInfo = await User.findOne({id:userId})

      const secret = uuid.v4().replace(/[-]/g,"")//生成的唯一秘钥

      const token_exp = 5
      //生成JSONWEBTOKEN
      const token = jwt.sign({ userId: userId }, secret, { expiresIn: token_exp })

      //将token存入cookie中传到客户端
      this.res.cookie('token', token, { maxAge: token_exp * 1000, httpOnly: true })

      const mtoken = md5(token) //将token进行md5加密减少字符串长度，方便存入Redis

      await sails.getDatastore('redis').leaseConnection(async (db)=>{
        await (util.promisify(db.setex).bind(db))(mtoken + ':secret', token_exp, secret)
      });

      return 'success'
    } catch (error){ //跳转到异常提示页面
      console.log(error)
      return 'exception'
    }
  }
};
